from collections import OrderedDict

from goods.models import GoodsChannel, GoodsChannelGroup


def get_categories():
    """
    提供商品频道和分类
    :return 菜单字典
    """
    # 查询商品频道和分类

    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:
        group_id = channel.group_id  # 当前组

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    # groups = GoodsChannelGroup.objects.all()
    #
    # # 先遍历出11个字典
    # for group in groups:
    #     categories[str(group.id)] = {"channels": [], "sub_cats": []}
    #
    # channels = GoodsChannel.objects.order_by("group_id", "sequence")
    #
    # for channel in channels:
    #     cat1 = channel.category
    #     cat1.url = channel.url
    #     categories[str(channel.group_id)]["channels"].append(cat1)
    #
    #     cat2_list = cat1.subs.all()  # 2级分类列表
    #     for cat2 in cat2_list:
    #         cat2.sub_cats = cat2.subs.all()
    #
    #     categories[str(channel.group_id)]["sub_cats"].extend(cat2_list)

    return categories
